package com.git.bcs.admin.bean.shiro.factory;

import com.git.bcs.admin.bean.shiro.ShiroUser;
import com.git.bcs.admin.system.entity.SysUser;
import com.git.bcs.admin.system.mapper.SysMenuMapper;
import com.git.bcs.admin.system.mapper.SysUserMapper;
import com.git.bcs.common.bean.holder.SpringContextHolder;

import org.apache.commons.collections.functors.ConstantFactory;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class ShiroFactroy implements IShiro {

	@Autowired
	private SysUserMapper userMapper;

	@Autowired
	private SysMenuMapper menuMapper;

	public static IShiro me() {
		return SpringContextHolder.getBean(IShiro.class);
	}

	@Override
	public SysUser user(String account) {
		// TODO Auto-generated method stub
		SysUser user = userMapper.getByAccount(account);

		// 账号不存在
		if (null == user) {
			throw new CredentialsException();
		}
		// 账号被冻结
		if (user.getStatus() != 1) {
			throw new LockedAccountException();
		}
		return user;
	}

	@Override
	public ShiroUser shiroUser(SysUser user) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<String> findPermissionsByRoleId(Integer roleId) {
		// TODO Auto-generated method stub
		return  menuMapper.getResUrlsByRoleId(roleId);
	}

	@Override
	public String findRoleNameByRoleId(Integer roleId) {
		// TODO Auto-generated method stub
		  return ConstantFactory.me().getSingleRoleTip(roleId);
	}

	@Override
	public SimpleAuthenticationInfo info(ShiroUser shiroUser, SysUser user, String realmName) {
		// TODO Auto-generated method stub
		String credentials = user.getPassword();

		// 密码加盐处理
		String source = user.getSalt();
		ByteSource credentialsSalt = new Md5Hash(source);
		return new SimpleAuthenticationInfo(shiroUser, credentials, credentialsSalt, realmName);
	}

}
